package controlador;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;

import controlador.FrontCommand;

/**
 * Servlet implementation class ControladorFrontal
 */
@WebServlet("/ControladorFrontal")
public class ControladorFrontal extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ControladorFrontal() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		   FrontCommand command = getCommand(request);
		   
		   command.init(getServletContext(), request, response);
		    try {
				command.process();
			
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}

	private FrontCommand getCommand (HttpServletRequest request)
	{
		try
		 {
		   return (FrontCommand) getCommandClass(request).newInstance();
		   
		 }catch (Exception e) {
			 throw null;
			
		 }
	}


	private Class getCommandClass(HttpServletRequest request)
	{
	Class result = null;
	final String commandClassName = "controlador."+(String) request.getParameter("command");
	try
	 {
	   result = Class.forName(commandClassName);
	 }
	catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		//e.printStackTrace();
		result = CommandNoEncontrado.class;
	 }
	 return result;
	}		
	
}
